<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      title="模板选择"
      width="600px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div class="container">
        <div class="left-table">
          <span>备选项</span>
          <div class="table">
            <el-form :inline="true" style="padding-left: 5px">
              <el-form-item>
                <el-select size="mini" v-model="formData.type" @change="onChangSelectType">
                  <el-option
                    v-for="(item, index) in templateConfig.type"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select size="mini" v-model="formData.templateTypeName" @change="onChangSelect">
                  <el-option
                    v-for="(item, index) in formData.templateType"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <div class="filter">
                  <el-input size="mini" v-model="formData.filter" placeholder="搜索名称"></el-input>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="mini" @click="onSearch">查询</el-button>
              </el-form-item>
            </el-form>

            <el-transfer
              ref="rxTransfer"
              class="transfer"
              v-model="transferValue"
              :data="data"
              :render-content="renderFunc"
              :titles="['表单应用', '确认数据']"
              @change="handleChange"
            ></el-transfer>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="processDialogVisible"
      title="修改权重"
      width="600px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <div class="qz_container">
        <rx-table
          ref="rxTable"
          v-if="isTable"
          :loading="loading"
          :isShowIndex="true"
          :tableData="templateAndSubTasks"
          :headers="headers"
          :height="tableHeight"
        ></rx-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialogProcess()">取 消</el-button>
        <el-button type="primary" @click="saveTaskWeight">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import RxTable from "./table/RxTable";
import { taskinfo } from "../mixins/taskinfo";

export default {
  name: "RxDialog",
  mixins: [taskinfo],
  components: { RxTable },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    tableData: {
      type: Array,
      default() {
        return [];
      },
    },
    operationStatus: {
      type: String,
      default: "",
    },
    templateId: {
      type: String,
      default: "",
    },
    id: {
      type: String,
      default: "",
    },
    opType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      formData: {
        type: "应用分类",
        templateType: [],
        templateTypeName: "",
        filter: "",
      },
      processDialogVisible: false, //流程全程窗口
      tempData: [], //临时数据
      data: [],
      transferValue: [],
      templateAndSubTasks: [],
      tableHeight: "350px",
      isTable: false,
      headers: [
        {
          key: "type",
          label: "数据类型",
          dictionaries: true,
        },
        {
          key: "name",
          label: "模板名称",
          dictionaries: false,
        },
        {
          key: "weight",
          label: "权重(%)",
          elWidth: "100px",
          type: "input",
          dictionaries: false,
        },
      ],
      loading: true,
      renderFunc(h, option) {
        return (
          <el-tooltip class="item" effect="dark" content={option.label} placement="top-start">
            {" "}
            <span> {option.label}</span>{" "}
          </el-tooltip>
        );
      },
    };
  },
  mounted() {
    this.initData();
  },

  methods: {
    //初始化显示穿梭框列表
    initData() {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].name == this.formData.type) {
          this.formData.templateType = this.tableData[i].data;
          this.tempData = this.tableData[i].data;
        }
      }
      if (this.formData.templateType.length > 0) {
        this.formData.templateTypeName = this.formData.templateType[0].name;
      }
      for (let i = 0; i < this.tempData.length; i++) {
        if (this.formData.templateTypeName == this.tempData[i].name) {
          for (let j = 0; j < this.tempData[i].templates.length; j++) {
            let tempData = this.tempData[i].templates[j];
            let param = {
              key: tempData.id,
              label: tempData.name,
            };
            this.data.push(param);
          }
        }
      }

      //编辑下回显右边列表模板数据
      if (this.operationStatus == "edit") {
        this.transferValue.push(this.templateId);
      }
    },
    //一级分类
    onChangSelectType(val) {
      this.formData.filter = "";
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].name == val) {
          this.formData.templateType = this.tableData[i].data;
          this.tempData = this.tableData[i].data;
        }
      }

      this.formData.templateTypeName =
        this.formData.templateType.length > 0 ? this.formData.templateType[0].name : "";
      this.onChangSelect(this.formData.templateTypeName);
    },
    //二级分类
    onChangSelect(val) {
      this.formData.filter = "";
      this.data = [];
      for (let i = 0; i < this.tempData.length; i++) {
        if (this.tempData[i].name == val) {
          let tempData = this.tempData[i].templates;
          for (let j = 0; j < tempData.length; j++) {
            let param = {
              key: tempData[j].id,
              label: tempData[j].name,
            };
            this.data.push(param);
          }
        }
      }
    },
    handleChange(value, direction, movedKeys, a) {
      this.transferValue = value;
    },

    save() {
      this.loadTemplateAndSubTasksList();
      this.transferValue.length > 0
        ? (this.processDialogVisible = true)
        : this.$message.warning("请选择模板！");
    },
    closeDialog() {
      this.$nextTick(() => {
        this.$refs.rxTransfer.clearQuery("right");
      });
      this.$emit("close-dialog");
    },
    closeDialogProcess() {
      this.processDialogVisible = false;
    },
    onSearch() {
      let tempData = [];
      if (this.formData.filter) {
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i].label.indexOf(this.formData.filter) != -1) {
            let param = {
              key: this.data[i].key,
              label: this.data[i].label,
            };
            tempData.push(param);
          }
        }
      }
      this.data = tempData;
    },
    //查询权流程重和子任务列表
    async loadTemplateAndSubTasksList() {
      this.loading = true;
      this.templateAndSubTasks = [];
      for (let i = 0; i < this.transferValue.length; i++) {
        for (let j = 0; j < this.tableData.length; j++) {
          if (this.tableData[j].name == this.formData.type) {
            let temps = this.tableData[j].data;
            for (let t = 0; t < temps.length; t++) {
              for (let k = 0; k < temps[t].templates.length; k++) {
                let val = temps[t].templates[k];
                if (this.transferValue[i] == val.id) {
                  let param = {
                    id: val.id,
                    name: val.name,
                    weight: 0,
                    type: 0,
                    col: val.col,
                  };
                  this.templateAndSubTasks.push(param);
                }
              }
            }
          }
        }
      }

      /*  if (this.opType != 'create') {
                      let res = await this.$http.query(`/seeyon/rest/bhtTask/children/${this.id}/0`);
                      let {data} = res
                      for (let i = 0; i < data.length; i++) {
                          let param = {
                              id: data[i].basicInfo.taskId,
                              name: data[i].basicInfo.title,
                              weight: (data[i].basicInfo.weight * 100),
                              type: 1,
                          }
                          this.templateAndSubTasks.push(param)
                      }
                      //计算百分比
                      let count = 100;

                      let result = count / this.templateAndSubTasks.length;


                      /!*for (let i = 0; i < this.templateAndSubTasks.length; i++) {
                          let number = this.templateAndSubTasks[i].weight
                          count -= number;
                      }

                      let tempArray = [] //流程数量
                      for (let i = 0; i < this.templateAndSubTasks.length; i++) {
                          let number = this.templateAndSubTasks[i].weight
                          if (number == 0) {
                              tempArray.push(number)
                          }
                      }

                      let result = parseInt(count / tempArray.length)

                      let ys = count % tempArray.length;

                      for (let i = 0; i < this.templateAndSubTasks.length; i++) {
                          let number = this.templateAndSubTasks[i].weight
                          if (number == 0) {
                              this.templateAndSubTasks[i].weight = Number(result);
                          }
                      }*!/


                      //  this.templateAndSubTasks[0].weight = this.templateAndSubTasks[0].weight + ys
                  }*/

      //现有流程列表
      this.loading = true;
      let res = await this.$http.query(`/seeyon/rest/taskDetail/process/${this.id}`);
      let { code, data } = res;
      if (code == 0) {
        for (let i = 0; i < data.length; i++) {
          let param = {
            id: data[i].id,
            name: data[i].templateName,
            weight: data[i].colWeight,
            type: 1,
          };
          this.templateAndSubTasks.push(param);
        }
      }

      let count = 100;

      let result = count / this.templateAndSubTasks.length;

      for (let i = 0; i < this.templateAndSubTasks.length; i++) {
        if (this.templateAndSubTasks[i].type == 0) {
          let number = this.templateAndSubTasks[i].weight;
          if (number == 0) {
            this.templateAndSubTasks[i].weight = Number(result.toFixed(2));
          }
        }
      }

      this.loading = false;
      this.isTable = true;
    },
    //保存流程和子任务权重
    saveTaskWeight() {
      let tableData = this.$refs["rxTable"].getData();
      let count = 0;
      /* let processData = []
                 let subTaskData = []*/
      let newData = [];
      let oldData = [];
      for (let i = 0; i < tableData.length; i++) {
        if (tableData[i].type == 0) {
          count += parseInt(tableData[i].weight);
        }
        tableData[i].type == 0 ? newData.push(tableData[i]) : oldData.push(tableData[i]);
      }

      //保存流程
      this.saveProcess(newData);
      //更新流程
      this.updateProcess(oldData);

      // if (count > 100) {
      //     this.$message.warning('新增数据权重超出100%');
      // } else {
      //     //保存流程
      //     this.saveProcess(newData);
      //     //更新流程
      //     this.updateProcess(oldData);
      // }
    },
    //保存流程
    saveProcess(processData) {
      let dataParams = {
        data: [],
        taskId: this.id,
      };
      for (let i = 0; i < processData.length; i++) {
        let param = {
          templateId: processData[i].id,
          templateName: processData[i].name,
          colWeight: processData[i].weight,
          col: processData[i].col,
        };
        dataParams.data.push(param);
      }
      this.$http.post("/seeyon/rest/taskDetail/process/insertBatch", dataParams).then((res) => {
        if (res.code == 0) {
          this.$message.success("保存成功！");
          this.processDialogVisible = false;
          this.$emit("close-dialog-table");
        } else {
          this.processDialogVisible = false;
          this.$message.error("保存失败！");
        }
      });
    },
    updateProcess(data) {
      let dataParams = {
        data: [],
        taskId: this.id,
      };
      for (let i = 0; i < data.length; i++) {
        let param = {
          id: data[i].id,
          colWeight: data[i].weight,
          name: data[i].name,
        };
        dataParams.data.push(param);
      }
      this.$http.post("/seeyon/rest/taskDetail/process/updateBatch", dataParams).then((res) => {
        if (res.code == 0) {
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: calc(100% - 40px);
  height: 360px;
  margin: auto;
  display: flex;
  justify-content: space-between;

  .left-table {
    width: 100%;
    height: 100%;
  }

  .table {
    width: 100%;
    height: 100%;
    border: 1px solid #ededed;
    border-radius: 5px;
  }

  .transfer {
    margin-left: 10px;
  }
}

.container /deep/ .el-input__inner {
  width: 150px;
  // padding-left: 5px;
}

.left-table /deep/ .el-transfer__buttons {
  display: inline-grid;
  padding: 0 25px;

  .el-button--primary.is-disabled,
  .el-button--primary.is-disabled:active,
  .el-button--primary.is-disabled:focus,
  .el-button--primary.is-disabled:hover {
    border-radius: 50%;
    height: 50px;
    width: 50px;
  }

  .el-button + .el-button {
    border-radius: 50%;
    height: 50px;
    width: 50px;
    margin-left: 0px;
    position: relative;
    top: -60px;
  }

  .el-transfer__button:first-child {
    border-radius: 50%;
    height: 50px;
    width: 50px;
    margin-left: 0px;
    position: relative;
    top: 60px;
  }

  .el-icon-arrow-left {
    margin-left: -3px;
  }

  .el-icon-arrow-right {
    margin-left: -3px;
  }
}

.container .filter /deep/ .el-input__inner {
  width: 115px;
}

.qz_container {
  width: 100%;
}
</style>
<style>
.el-dialog__header {
  background: aliceblue;
}

.el-dialog__title {
  font-size: 15px;
}
</style>
